<?php

namespace app\job;

use app\admin\service\DouYinService;
use think\facade\Db;
use think\facade\Log;
use think\queue\Job;

/**
 * 抖小媒资小程序授权
 * Class DyMediaAppletAuthorize
 * @package app\job
 */
class DyMediaAppletAuthorize
{
    private $service;

    public function __construct(
        DouYinService $service
    ){
        $this->service = $service;
    }

    /**
     * 小程序授权任务
     * @param Job $job
     * @param array $info
     */
    public function fire(Job $job, array $info)
    {
        $appletIds = $info['applet_ids'] ?? [];
        $id = $info['id'] ?? '';
        if (empty($appletIds) || empty($id)) {
            $job->delete();
            return;
        }

        try {
            $dyVideo = Db::name('third_videos')
                ->field('id,album_id,applet_ids,video_id')
                ->where('id', $id)->where('platform', 2)
                ->find();

            $applets = Db::name('applet')
                ->whereIn('id', $appletIds)->where('type',2)
                ->column('app_id', 'id');

            if (empty($dyVideo) || empty($applets)) {
                $job->delete();
                return;
            }

            //1、页面绑定
            $failApplets = $this->dyOtherPageBinding($dyVideo, $applets);
            foreach ($applets as $aid => $appid) {
                if (isset($failApplets[$aid])) {
                    unset($applets[$aid]);
                }
            }
            //2、小程序授权
            $app_ids = array_keys($applets);
            $app_keys = array_values(array_filter($applets));
            $res = $this->service->shortPlayAuthorize($dyVideo['album_id'], $app_keys);
            if (!empty($res['msg'])) {
                $msg = json_encode(['third_video_id' => $id, 'applet_ids' => $app_ids, 'msg' => $res['msg']], JSON_UNESCAPED_UNICODE);
                Log::channel('tiktok')->log('info','抖小媒资授权失败,'. $msg);
                Db::name('third_videos')->where('id', $dyVideo['id'])->update(['task_status' => 2]);
                $job->delete();
                return;
            }

            Db::name('third_videos')->where('id', $dyVideo['id'])
                ->update([
                    'is_authorize' => 1,
                    'applet_ids' => json_encode($app_ids),
                    'task_status' => 2
                ]);

            Log::channel('tiktok')->log('info', '抖小媒资授权成功,'. json_encode(['third_video_id' => $id, 'applet_ids' => $app_ids]));
            $job->delete();

        } catch (\Exception $e) {
            $job->delete();
            Log::channel('tiktok')->log('error','****** ' . json_encode($info) . ' --//-- ' . '第 ' . $e->getLine() . ' 行' . '：' . $e->getMessage());
        }
    }

    //其他小程序页面绑定
    public function dyOtherPageBinding($thirdVideo, $applets): array
    {
        $details = Db::name('video_details')
            ->field('id,platform_config')
            ->where('video_id', $thirdVideo['video_id'])
            ->select()
            ->toArray();

        if (!$details) return [];

        $bindAppletIds = Db::name('dy_page_bind_records')
            ->where('video_id', $thirdVideo['video_id'])
            ->where('is_page_bind',1)
            ->column('applet_id');

        $failApplets = [];
        $time = time();
        foreach ($applets as $aid => $appid) {
            if ($this->service->douyinConf['appid'] == $appid) {
                continue;
            }
            if (in_array($aid, $bindAppletIds)) {
                continue;
            }

            $text = '';
            foreach ($details as $detail) {
                $platformConf = !empty($detail['platform_config']) ? json_decode($detail['platform_config'], true): [];
                $platformConf2 = $platformConf['douyinyun'] ?? [];
                $episode_id = $platformConf2['episode_id'] ?? '';
                if (!$episode_id) {
                    $failApplets[$aid] = $appid;
                    $text = '剧集存在无episode_id值,detail_id:' . $detail['id'];
                    break;
                }

                $result = $this->service->pageBanding(
                    $thirdVideo['album_id'],
                    $episode_id,
                    ['video_id' => $thirdVideo['video_id'], 'detail_id' => $detail['id'], 'app_id' => $appid]
                );

                if ($result['msg']) {
                    $failApplets[$aid] = $appid;
                    $text = $result['msg'];
                    break;
                }
            }

            if (!empty($text)) {
                $msg = json_encode(['third_video_id' => $thirdVideo['id'], 'applet_id' => $aid, 'msg' => $text], JSON_UNESCAPED_UNICODE);
                Log::channel('tiktok')->log('info','抖小媒资页面绑定失败：'. $msg);
            }

            $pageBindId = Db::name('dy_page_bind_records')
                ->where('video_id', $thirdVideo['video_id'])
                ->where('applet_id', $aid)
                ->value('id');

            $recordTable = Db::name('dy_page_bind_records');
            $data = [
                'is_page_bind' => empty($text) ? 1 : 0,
                'updated_at' => $time,
                'content' => $text
            ];
            if ($pageBindId) {
                $recordTable->where('id', $pageBindId)->update($data);
            } else {
                $recordTable->insert(array_merge($data, [
                    'video_id' => $thirdVideo['video_id'],
                    'album_id' => $thirdVideo['album_id'],
                    'applet_id' => $aid,
                    'created_at' => $time
                ]));
            }
        }

        return $failApplets;
    }

}